import os
from pathlib import Path
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, declarative_base


def _default_sqlite_url() -> str:
    """Return an absolute SQLite URL pointing to server/db/autobuild.db.

    Using an absolute path ensures the database file is created inside the
    repository regardless of the current working directory (e.g. when the
    app is started from the repo root via run_backend.ps1).
    """

    server_dir = Path(__file__).resolve().parents[2]  # points to .../server
    db_dir = server_dir / "db"
    db_dir.mkdir(parents=True, exist_ok=True)
    sqlite_path = db_dir / "autobuild.db"
    # SQLAlchemy expects forward slashes for sqlite URLs on Windows as well
    return f"sqlite:///{sqlite_path.as_posix()}"


# Read database URL from environment, fallback to absolute SQLite file path
SQLALCHEMY_DATABASE_URL = os.environ.get("DATABASE_URL") or _default_sqlite_url()

# For SQLite, connect_args required to allow multithreading
connect_args = {}
if SQLALCHEMY_DATABASE_URL.startswith("sqlite"):
    connect_args = {"check_same_thread": False}

engine = create_engine(SQLALCHEMY_DATABASE_URL, connect_args=connect_args)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()

# Dependency to get DB session in FastAPI endpoints
def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()
